using Furion;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using DbType = SqlSugar.DbType;

namespace tlBasic.Core;

public static class SqlSugarSetup
{
    /// <summary>
    /// Sqlsugar 上下文初始化
    /// </summary>
    /// <param name="services"></param>
    public static void AddSqlSugarSetup(this IServiceCollection services)
    {
        var dbOptions = App.GetOptions<DbConnectionOptions>();
        var configureExternalServices = new ConfigureExternalServices
        {
            EntityService = (type, column) => // 修改列可空-1、带?问号 2、String类型若没有Required
            {
                if ((type.PropertyType.IsGenericType && type.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    || (type.PropertyType == typeof(string) && type.GetCustomAttribute<RequiredAttribute>() == null))
                    column.IsNullable = true;
            }
        };
        dbOptions.ConnectionConfigs.ForEach(config =>
        {
            config.ConfigureExternalServices = configureExternalServices;
        });

        SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs, db =>
        {
            dbOptions.ConnectionConfigs.ForEach(config =>
            {
                var dbProvider = db.GetConnectionScope((string)config.ConfigId); 
                // 设置超时时间
                dbProvider.Ado.CommandTimeOut = 60;

                // 打印SQL语句
                dbProvider.Aop.OnLogExecuting = (sql, pars) =>
                {
                    if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
                        Console.ForegroundColor = ConsoleColor.Green;
                    if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
                        Console.ForegroundColor = ConsoleColor.White;
                    if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
                        Console.ForegroundColor = ConsoleColor.Blue;
                    Console.WriteLine("【" + DateTime.Now + "——执行SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, sql, pars) + "\r\n");
                      };
                dbProvider.Aop.OnError = (ex) =>
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
                    Console.WriteLine("【" + DateTime.Now + "——错误SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
                  };

                // 数据审计
                dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
                {
                    // 新增操作
                    if (entityInfo.OperationType == DataFilterType.InsertByObject)
                    {
                        // 主键(long类型)且没有值的---赋值雪花Id
                        if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
                        {
                            var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
                            if (id == null || (long)id == 0)
                                entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId());
                        }
                        if (entityInfo.PropertyName == EntityConst.CreatedTime)
                            entityInfo.SetValue(DateTime.Now);
                        if (App.User != null)
                        { 
                            if (entityInfo.PropertyName == EntityConst.CreatedUserId)
                                entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
                            if (entityInfo.PropertyName == EntityConst.CreatedUserName)
                                entityInfo.SetValue(App.User.FindFirst(ClaimConst.Name)?.Value);
                        }
                    }
                // 更新操作
                if (entityInfo.OperationType == DataFilterType.UpdateByObject)
                {

                    if (entityInfo.PropertyName == EntityConst.UpdatedTime)
                        entityInfo.SetValue(DateTime.Now);
                    if (entityInfo.PropertyName == EntityConst.UpdatedUserId)
                        entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
                    if (entityInfo.PropertyName == EntityConst.UpdatedUserName)
                        entityInfo.SetValue(App.User?.FindFirst(ClaimConst.Name)?.Value);
 
                        
                    }
                };

                // 差异日志
                dbProvider.Aop.OnDiffLogEvent = async u =>
                {
                    if (!dbOptions.EnableDiffLog) return;
                };

                // 配置实体假删除过滤器
                SetDeletedEntityFilter(dbProvider);
                // 配置租户实体过滤器
                // SetTenantEntityFilter(dbProvider);
            });
        });

       

        services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
        services.AddScoped(typeof(SqlSugarRepository<>)); // 注册仓储
        services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 注册事务与工作单元
    }

     

    /// <summary>
    /// 配置实体假删除过滤器
    /// </summary>
    public static void SetDeletedEntityFilter(SqlSugarScopeProvider db)
    {
        // 获取所有继承基类数据表集合
        var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
            && (u.BaseType == typeof(DEntityTenant) || u.BaseType == typeof(DEntityBase) ));
        if (!entityTypes.Any()) return;

        foreach (var entityType in entityTypes)
        {
            Expression<Func<DEntityBase, bool>> dynamicExpression = u => u.IsDeleted == false;
            db.QueryFilter.Add(new TableFilterItem<object>(entityType, dynamicExpression,true));
        }
    }

    /// <summary>
    /// 配置租户实体过滤器
    /// </summary>
    public static void SetTenantEntityFilter(SqlSugarScopeProvider db)
    {
        // 获取租户实体数据表集合
        var dataEntityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
            && u.BaseType == typeof(DEntityTenant));
        if (!dataEntityTypes.Any()) return;

        var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
        if (string.IsNullOrWhiteSpace(tenantId)) return;

        foreach (var dataEntityType in dataEntityTypes)
        {
            Expression<Func<DEntityTenant, bool>> dynamicExpression = u => u.TenantId == long.Parse(tenantId);
            db.QueryFilter.Add(new TableFilterItem<object>(dataEntityType, dynamicExpression, true));
        }
    }
}